package de.wbh.gwt.form.layouter.shared.activity;

import javax.inject.Inject;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.inject.client.AsyncProvider;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

import de.wbh.gwt.form.layouter.gwt.rpc.ConfigurationServiceAsync;
import de.wbh.gwt.form.layouter.shared.place.CreateConfigurationPlace;
import de.wbh.gwt.form.layouter.shared.place.EditPlace;

public class SaveConfigurationActivity extends AbstractActivity implements SaveConfigurationView.Presenter {

	private final AsyncProvider<SaveConfigurationView> viewProvider;
	private final PlaceController placeController;

	private SaveConfigurationView view;
	private final ConfigurationServiceAsync configurationService;

	@Inject
	public SaveConfigurationActivity(AsyncProvider<SaveConfigurationView> viewProvider, ConfigurationServiceAsync configurationService, PlaceController placeController) {
		this.viewProvider = viewProvider;
		this.placeController = placeController;
		this.configurationService = configurationService;
	}

	@Override
	public void save(String name) {
		CreateConfigurationPlace place = (CreateConfigurationPlace) this.placeController.getWhere();
		this.configurationService.createConf(name, place.getEfdName(), place.getPdfName(), new AsyncCallback<Void>() {
			@Override
			public void onFailure(Throwable caught) {
				caught.printStackTrace();
			}

			@Override
			public void onSuccess(Void result) {
				// TODO Auto-generated method stub

			}
		});

		this.placeController.goTo(new EditPlace(place.getEfdName(), place.getPdfName(), name));
	}

	@Override
	public void start(final AcceptsOneWidget panel, EventBus eventBus) {
		this.viewProvider.get(new AsyncCallback<SaveConfigurationView>() {

			@Override
			public void onFailure(Throwable caught) {
				caught.printStackTrace();
			}

			@Override
			public void onSuccess(SaveConfigurationView result) {
				SaveConfigurationActivity.this.view = result;
				SaveConfigurationActivity.this.view.setPresenter(SaveConfigurationActivity.this);
				panel.setWidget(SaveConfigurationActivity.this.view);
			}
		});
	}

}
